<?php

namespace App\Admin\Middleware;

use App\Admin\Services\GrantService;
use Closure;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Route;

class InitAdminMenu
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request $request
     * @param  \Closure                 $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        // 已登入用户
        if (auth('admin')->check()) {
            $user = auth('admin')->user();
            // 根據路由配置獲取菜單
            $menus = Cache::remember('admin:menus:' . auth('admin')->id(), now()->addMinute(1), function () use ($user) {
                $permissions = (new GrantService)->getRoutes($user);
                $routes      = Route::getRoutes();
                $menus       = [];

                foreach ($routes as $route) {
                    // 解析菜單
                    if (
                        !isset($route->action['domain'])
                        || $route->action['domain'] != config('admin.route.domain')
                        || !isset($route->action['menu'])
                        || !$route->getName()
                    ) {
                        continue;
                    }

                    // 判斷權限
                    if (!in_array('*', $permissions) && !in_array($route->getName(), $permissions)) {
                        continue;
                    }

                    [$group, $name] = explode(':', $route->action['menu'], 2);

                    if (!isset($menus[$group])) {
                        $menus[$group] = [];
                    }

                    $menus[$group][] = [
                        'name'  => $name,
                        'url'   => broute($route->getName()),
                        'route' => $route->getName(),
                    ];
                };

                return $menus;
            });
            // 模板賦值
            view()->share('_route_menus', $menus);
        }

        return $next($request);
    }
}
